/*
 * Created by SharpDevelop.
 * User: Dror B. Helper
 * Date: 01/10/2008
 * Time: 22:28
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System.IO;
using System.IO.IsolatedStorage;
using System.Xml.Serialization;

namespace StackOverflowClient
{
	/// <summary>
	/// Description of UserArchive.
	/// </summary>
	internal class UserArchive
	{
	    readonly IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore
			(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null );


	    private static string FileNameFromUserName(string userName)
        {
            return userName + ".xml";
        }
		public void Save(UserDescriptor user)
		{
			using(var oStream =
                  new IsolatedStorageFileStream(FileNameFromUserName(user.Name), FileMode.Create, isoStore))
			{

				var xmls = new XmlSerializer(typeof(UserDescriptor));
				xmls.Serialize(oStream, user);
			}
		}
		
		public bool Exist(string userName)
		{
		    string fileNameToFind = FileNameFromUserName(userName);

            string[] fileNames = isoStore.GetFileNames(fileNameToFind);

			foreach ( var fileName in fileNames )
			{
                if (fileName == fileNameToFind)
				{
					return true;
				}
			}
			
			return false;
		}
		
		public UserDescriptor Load(string userName)
		{
			var userFileName = FileNameFromUserName(userName);
			UserDescriptor userDescriptor = null;
            if (Exist(userName) == false)
			{
				return userDescriptor;
			}

            using (var iStream = new IsolatedStorageFileStream(userFileName,FileMode.Open, isoStore))
            {

                using (var reader = new StreamReader(iStream))
                {
                    var xmlS = new XmlSerializer(typeof (UserDescriptor));
                    userDescriptor = (UserDescriptor) xmlS.Deserialize(reader);
                }
            }

		    return userDescriptor;
		}

	    public void Delete(string userName)
	    {
            isoStore.DeleteFile(FileNameFromUserName(userName));
	    }
	}
}